package com.jabo.douban.demo.domain.http;

import android.util.Log;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * @anthor JZheng3
 * @Time: 2020/3/2
 */
@SuppressWarnings("NullableProblems")
public class HttpInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        String url = request.url().toString();
        String method = request.method();

        //添加固定参数
        HttpUrl.Builder urlBuilder = request.url().newBuilder()
                .scheme(request.url().scheme())
                .host(request.url().host())
                .addQueryParameter("key", "20ed61e89fae5b9f0733ece971ba10f8");

        // 新的请求
        Request newRequest = request.newBuilder()
                .method(request.method(), request.body())
                .url(urlBuilder.build())
                .build();

        //用新请求获取回复
        Response response = chain.proceed(newRequest);
        ResponseBody responseBody = response.peekBody(Long.MAX_VALUE);
        byte[] inputStream = responseBody.bytes();
        String responseString = new String(inputStream);

        Log.e("HttpInterceptor", "currentThread: " + Thread.currentThread());
        Log.e("HttpInterceptor", "method: " + method);
        Log.e("HttpInterceptor", "url: " + url);
        Log.e("HttpInterceptor", "responseString: " + responseString);

        return response;
    }
}
